package com.servlet.resp; /**
 * @author wzm
 * @create 2024-01-27 16:13
 * project_name:JavaWeb2401
 * @Description 响应字节数据
 */

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/resp3")
public class ResponseServlet3 extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
     //响应一个图片文件到浏览器  步骤：获得response对象的字节输出流 将数据写到前端

        //1.读取文件输入流
        FileInputStream fis = new FileInputStream("d://a.jpeg");//8848


        //2.获取response字节输出流对象
        ServletOutputStream os = response.getOutputStream();

        //3.输出 从输入流中读取写到输出流中
        //定义一个字节数组
        byte[] buff = new byte[1024];
        //当输入流中的字节数据已经没有了时，循环结束  读取到的长度为-1

        int read = 0;//读取到的字节数
        while((read = fis.read(buff)) != -1){
            //每次读到一点数据就将数据响应到前端
            os.write(buff,0,read);

        }
        //4.关闭资源
        fis.close();


    }
}
